package scau.gsmg.misp.service.impl;

import java.util.List;
import javax.annotation.Resource;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Service;

import scau.gsmg.misp.service.ILoginService;
import scau.gsmg.misp.utils.IncorrectCaptchaException;
import scau.gsmg.misp.utils.UsernamePasswordCaptchaToken;
import scau.gsmg.misp.vo.Permission;
import scau.gsmg.misp.vo.Role;
import scau.gsmg.misp.vo.User;

/**
 * 用户登录授权service(shrioRealm)
 * 
 */
/**
 * @Title: UserRealmService.java
 * @Group: GaoShenMenGui
 * @Date: 2015-6-1
 */
@Service
public class UserRealmService extends AuthorizingRealm {

	private ILoginService loginService;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		// 获取当前用户
		User u = (User) principals.getPrimaryPrincipal();
		// Role role ;
		List<Role> list = loginService.searchRole(u);
		// 创建授权信息实体
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		// 获取用户角色并添加到授权信息实体
		// 赋予角色
		for (Role role : list) {
		//	authorizationInfo.addRole(role.getRoleCode());
			List<Permission> listPermission = loginService.findPermissions(role
					.getId());
			if (listPermission != null && listPermission.size() != 0) {
				for (int i = 0; i < listPermission.size(); i++) {
					authorizationInfo.addStringPermission(listPermission.get(i)
							.getPermCode());
				}
			}
		}
		// 此处处理完成可以放入一些额外的通用信息到session中
		return authorizationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {

		UsernamePasswordCaptchaToken passwordToken = (UsernamePasswordCaptchaToken) token;
		User user = new User();
		if (passwordToken.getUsername() != null) {
			user.setLoginID(passwordToken.getUsername());
		}
		if (doCaptchaValidate(passwordToken)) {
			user = loginService.login(user);
			// 一些前置处理，判断帐号是否存在，帐号是否锁定
			if (user != null) {
				// 设置用户session
				Session session = SecurityUtils.getSubject().getSession();
				session.setAttribute("user", user);
				return new SimpleAuthenticationInfo(user, user.getPassword(),
						getName());
			}
		}
		return null;
	}

	/**
	 * 验证码校验
	 * 
	 * @param token
	 * @return boolean
	 */
	protected boolean doCaptchaValidate(UsernamePasswordCaptchaToken token) {
		String captcha = (String) SecurityUtils
				.getSubject()
				.getSession()
				.getAttribute(
						com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
		System.out.println(captcha + token.getCaptcha());
		if (captcha != null && !captcha.equalsIgnoreCase(token.getCaptcha())) {
			throw new IncorrectCaptchaException("验证码错误！");
		}
		return true;
	}

	public ILoginService getLoginService() {
		return loginService;
	}

	@Resource
	public void setLoginService(ILoginService loginService) {
		this.loginService = loginService;
	}

}
